package com.pgytesting.secondhandcar.controller.controller;

import com.pgytesting.secondhandcar.util.UtilMethod;
import com.pgytesting.secondhandcar.vo.Parameters;
import com.pgytesting.secondhandcar.vo.ResponseMessage;
import com.pgytesting.secondhandcar.vo.SMSCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : frosty0804@gmail.com
 * @version : v1.0
 * @projectName : secondhandcar
 * @className : SMSCodeController
 * @description : TODO(一句话描述该类的功能)
 * @date : 2019/8/16 15:40
 */
@Slf4j
@RestController
public class SMSCodeController {
    /**
     * 获取短信验证码
     *
     * @param code          验证码
     * @param bindingResult 参数校验
     * @param httpSession   session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSMSCode", method = RequestMethod.POST)
    public ResponseMessage getSMSCode(@Valid @RequestBody SMSCode code, BindingResult bindingResult, HttpSession httpSession) {
        if (bindingResult.hasErrors()) {
            String msg = bindingResult.getFieldError().getDefaultMessage();
            return ResponseMessage.errorResponse(msg);
        }
        SMSCode smsCode = new SMSCode();
        smsCode.setSmsCode(UtilMethod.randomCode());
        smsCode.setPhoneNumber(code.getPhoneNumber());
        smsCode.setCurrentTime(UtilMethod.unixLong() + Parameters.FIVE_MINUTES);
        httpSession.setAttribute("SMSCode", smsCode);
        Map<String, Object> map = new HashMap();
        map.put("SMSCode", smsCode.getSmsCode());
        map.put("Message", String.format("验证码有效期5分钟，请在%s前使用", UtilMethod.getUnixToTime(smsCode.getCurrentTime())));
        return ResponseMessage.successResponse(map, "获取短信验证码成功");
    }
}
